import sys
from pathlib import Path

root_dir = Path(__file__).parent.resolve()  # import bookstore dir
sys.path.insert(0, str(root_dir))

import logging
from be.model.store import init_database, get_db_conn, get_db_mongo
from sqlalchemy import text

logging.basicConfig(level=logging.INFO) # logging level

def test_create_tables():
    try:

        init_database()

        conn = get_db_conn() # postgresql

        result = conn.execute(
    text("SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'")
)
        tables = [row[0] for row in result]

        logging.info("Tables in PostgreSQL: %s", tables)

        expected_tables = ['users', 'user_store', 'store_book', 'orders', 'order_book', 'book']
        for table in expected_tables:
            if table not in tables:
                logging.error(f"Table {table} not found")
                return False
            else:
                logging.info(f"Table {table} found")


        mongo_db = get_db_mongo() # mongodb

        collections = mongo_db.list_collection_names()

        logging.info("Collections in MongoDB: %s", collections)
        if "book_details" not in collections:
            logging.error("book_details collection not found")
            return False
        else:
            logging.info("book_details collection found")

        # all ok
        logging.info("All tables and collections ok")
        return True

    except Exception as e:
        logging.error("Error during  tab and col testing: %s", str(e))
        return False

if __name__ == "__main__":
    success = test_create_tables()
    if success:
        logging.info("Database setup all ok")
    else:
        logging.error("Database setup not ok")
